package logic

import (
	"context"
	"errors"
	"short-video-manager/models/cache"
	"short-video-manager/models/mysql"
	"short-video-manager/pkg"

	"short-video-manager/videorpc/internal/svc"
	"short-video-manager/videorpc/videorpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *videorpc.LoginRequest) (*videorpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	var user mysql.UserInfo

	if err := user.FindUserByPhone(mysql.DB, in.PhoneNum); err != nil {
		return nil, errors.New("手机号码已存在,可直接登录")
	}
	if in.LoginType == 1 {
		result, _ := cache.Rdb.Get(l.ctx, "smsCode"+in.PhoneNum).Result()
		if result != in.SmsCode {
			return nil, errors.New("验证码不正确")
		}
		if result == "" {
			return nil, errors.New("短信验证码过期，请重新发送")
		}
	}
	if in.LoginType == 2 {
		if pkg.Md5(in.Pwd) != user.Pwd {
			return nil, errors.New("密码不正确")
		}
	}
	if user.AccountStatus == 1 {
		return nil, errors.New("账号已禁用，请联系管理员")
	}
	return &videorpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
